package com.dymall.controller;

import cn.hutool.core.bean.BeanUtil;
import com.dymall.common.utils.UserContext;
import com.dymall.domain.dto.CartFormDTO;
import com.dymall.domain.po.Cart;
import com.dymall.domain.vo.CartVO;
import com.dymall.service.CartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "购物车相关接口")
@RestController
@RequestMapping("/carts")
@RequiredArgsConstructor
public class CartController {
    private final CartService cartService;
    private final StringRedisTemplate stringRedisTemplate;

    @ApiOperation("查询购物车列表")
    @GetMapping
    public List<CartVO> queryMyCarts(){
        //添加redis缓存
        return cartService.queryMyCarts();
    }

    @ApiOperation("添加商品到购物车")
    @PostMapping
    public void addItemToCart(@RequestBody CartFormDTO cartFormDTO){
        cartService.addItemToCart(cartFormDTO);
    }

    @ApiOperation("更新购物车数据")
    @PutMapping
    public void updateCart(@RequestBody Cart cart){
        cartService.updateById(cart);
        // 删除redis中的缓存
        stringRedisTemplate.delete("cart:" + UserContext.getUser());
    }

    @ApiOperation("批量删除购物车中商品")
    @ApiImplicitParam(name = "ids", value = "购物车条目id集合")
    @DeleteMapping
    public void deleteCartItemByIds(@RequestParam("ids") List<Long> ids){
        cartService.deleteCartItemByIds(ids);
    }

    @ApiOperation("删除购物车中商品")
    @DeleteMapping("{id}")
    public void deleteCartItem(@Param("购物车条目id")@PathVariable("id") Long id){
        cartService.removeById(id);
        // 删除redis中的缓存
        stringRedisTemplate.delete("cart:" + UserContext.getUser());
    }
}